const { Model, DataTypes } = require('sequelize');
const sequelize = require('../db/db');

class QuestionComment extends Model { }
QuestionComment.init(
  {
    id: {
      type: DataTypes.CHAR(18),
      primaryKey: true,
      allowNull: false,
      comment: '评论ID'
    },
    question_id: {
      type: DataTypes.CHAR(18),
      allowNull: false,
      comment: '题目ID'
    },
    user_id: {
      type: DataTypes.CHAR(18),
      allowNull: false,
      comment: '用户ID'
    },
    content: {
      type: DataTypes.TEXT,
      allowNull: false,
      comment: '评论内容'
    },
    difficulty_rating: {
      type: DataTypes.TINYINT,
      allowNull: true,
      validate: { min: 1, max: 5 },
      comment: '难度评分(1-5)'
    },
    quality_rating: {
      type: DataTypes.TINYINT,
      allowNull: true,
      validate: { min: 1, max: 5 },
      comment: '质量评分(1-5)'
    },
    likes: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
      comment: '点赞数'
    },
    create_time: {
      type: DataTypes.DATE,
      defaultValue: DataTypes.NOW,
      comment: '创建时间'
    },
    update_time: {
      type: DataTypes.DATE,
      comment: '更新时间'
    }
  },
  {
    sequelize,
    modelName: 'QuestionComment',
    tableName: 'question_comment',
    timestamps: false,
  }
);

// 关联关系在模型定义后设置，避免循环依赖
const setupAssociations = () => {
  const User = require('./User');
  const Question = require('./Question');
  
  QuestionComment.belongsTo(User, {
    foreignKey: 'user_id',
    targetKey: 'user_id',
    as: 'user'
  });

  QuestionComment.belongsTo(Question, {
    foreignKey: 'question_id',
    targetKey: 'id',
    as: 'question'
  });
  
  // 添加对CommentLike的关联，修改关联名称为likeRecords避免与属性冲突
  QuestionComment.hasMany(require('./CommentLike'), {
    foreignKey: 'comment_id',
    sourceKey: 'id',
    as: 'likeRecords'
  });
};

// 在其他模型加载完成后调用关联设置
setTimeout(setupAssociations, 0);

module.exports = QuestionComment; 